package widget.rapid.bucuresti;

import widget.rapid.bucuresti.R;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.widget.RemoteViews;

public class RapidWidget extends AppWidgetProvider {
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
        AppWidgetManager appmanager = AppWidgetManager.getInstance(context);

        for (int wid : appWidgetIds) {
            System.out.println("[onUpdate] for widget id: " + wid);
            RemoteViews rView = new RemoteViews(context.getPackageName(), R.layout.widget);

            SharedPreferences prefs = Prefs.get(context);
            int resID = prefs.getInt(String.valueOf(wid), -1);
            if (resID != -1) {
                rView.setImageViewResource(R.id.widgetImageView, resID);
            }

            Intent intent = new Intent(context, RapidActivity.class);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, wid);

            PendingIntent pendingIntent = PendingIntent.getActivity(context, wid, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            rView.setOnClickPendingIntent(R.id.widgetImageView, pendingIntent);
            appmanager.updateAppWidget(wid, rView);
        }
    }

    @Override
    public void onEnabled(Context context) {
        AppWidgetManager appmanager = AppWidgetManager.getInstance(context);
        ComponentName cmpName = new ComponentName(context, RapidWidget.class);
        int[] widgetIds = appmanager.getAppWidgetIds(cmpName);

        onUpdate(context, appmanager, widgetIds);
    }

    @Override
    public void onDisabled(Context context) {
        // clear prefs
        SharedPreferences prefs = Prefs.get(context);
        Editor editor = prefs.edit();
        
        editor.clear();
        editor.commit();
    }
}
